package com.ruoyi.school.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.enums.FileTypeEnum;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileTypeUtils;
import com.ruoyi.school.domain.*;
import com.ruoyi.school.domain.vo.*;
import com.ruoyi.school.enums.AuditStatusEnum;
import com.ruoyi.school.enums.AuditTypeEnum;
import com.ruoyi.school.enums.WallStateEnum;
import com.ruoyi.school.handler.wall.WallTopThree;
import com.ruoyi.school.service.*;
import com.ruoyi.school.mapper.PacScientificProjectsMapper;
import com.ruoyi.school.utils.CommonUtils;
import com.ruoyi.system.domain.TableData;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * @author jeremylin
 * @description 针对表【pac_scientific_projects(大创科研项目)】的数据库操作Service实现
 * @createDate 2025-07-10 22:22:14
 */
@Service
public class PacScientificProjectsServiceImpl extends ServiceImpl<PacScientificProjectsMapper, PacScientificProjects>
        implements PacScientificProjectsService {
    @Resource
    private StudentService studentService;

    @Resource
    private PacAuditRecordsService pacAuditRecordsService;

    @Resource
    private PacTeacherService pacTeacherService;

    @Resource
    private PacScientificProjectsParticipationService pacScientificProjectsParticipationService;


    @Resource
    private PacClassTeacherService pacClassTeacherService;

    @Override
    public TableData<PacAcademicOutputVo> getList(PacAcademicOutputVo academicOutput) {
        // 查询学生信息
        Student studentParams = new Student();
        studentParams.setStuPhone(academicOutput.getStuPhone());
        studentParams.setStuFaculties(academicOutput.getStuFaculties());
        studentParams.setYearEnrollment(academicOutput.getYearEnrollment());
        studentParams.setStuClass(academicOutput.getStuClass());

        if(academicOutput.getTeacherType() != null){
            List<PacClassInfoVo> pacClassInfoVos;
            if(academicOutput.getTeacherType() == 0){
                // 获取当前老师绑定的班级id
                pacClassInfoVos = pacClassTeacherService.selectByTeacherByKey(getLoginUser().getUser(),"teacher");
            }else if(academicOutput.getTeacherType() == 1){
                pacClassInfoVos = pacClassTeacherService.selectByTeacherByKey(getLoginUser().getUser(),"teacher2");
            }else{
                pacClassInfoVos = pacClassTeacherService.selectByTeacherByKey(getLoginUser().getUser(),"duizhang");
            }
            if(pacClassInfoVos != null && !pacClassInfoVos.isEmpty()){
                List<Integer> classIds = pacClassInfoVos.stream().map(PacClass::getId).collect(Collectors.toList());
                // 设置当前老师可以查询的班级
                studentParams.setClassIds(classIds);
            }

            if (pacClassInfoVos.isEmpty()) {
                return TableData.<PacAcademicOutputVo>builder()
                        .total(0L)
                        .build();

            }
        }


        List<Student> studentSearch = studentService.selectInfo(studentParams);
        if (!studentSearch.isEmpty()) {
            List<Integer> ids = studentSearch.stream().map(Student::getId).collect(Collectors.toList());
            academicOutput.setStuIds(ids);
        }
        startPage();
//        List<PacScientificProjects> list = lambdaQuery()
//                .likeRight(StringUtils.isNotEmpty(academicOutput.getStuName()), PacScientificProjects::getStuName, academicOutput.getStuName())
//                .eq(StringUtils.isNotEmpty(academicOutput.getStuNum()), PacScientificProjects::getStuNum, academicOutput.getStuNum())
//                .eq(Objects.nonNull(academicOutput.getAcAudit()), PacScientificProjects::getAcAudit, academicOutput.getAcAudit())
//                .eq(Objects.nonNull(academicOutput.getAcWall()), PacScientificProjects::getAcWall, academicOutput.getAcWall())
//                .eq(Objects.nonNull(academicOutput.getStuId()), PacScientificProjects::getStuId, academicOutput.getStuId())
//                .eq(Objects.nonNull(academicOutput.getAcTime()), PacScientificProjects::getAcTime, academicOutput.getAcTime())
//                .eq(Objects.nonNull(academicOutput.getInputValue1()), PacScientificProjects::getInputValue1, academicOutput.getInputValue1())
//                .likeRight(Objects.nonNull(academicOutput.getAcTitle()), PacScientificProjects::getAcTitle, academicOutput.getAcTitle())
//                .eq(Objects.nonNull(academicOutput.getAcDanwei()), PacScientificProjects::getAcDanwei, academicOutput.getAcDanwei())
//                .in(Objects.nonNull(academicOutput.getStuIds()), PacScientificProjects::getStuId, academicOutput.getStuIds())
//                .list();
        List<PacScientificProjects> list = baseMapper.getList(academicOutput);
        // 找到学生id
        List<Long> stuIds = list.stream().map(PacScientificProjects::getStuId).collect(Collectors.toList());
        List<Student> students = studentService.selectByStuIds(stuIds);
        Map<Integer, Student> studentMap = students.stream().collect(Collectors.toMap(Student::getId, student -> student));
        ArrayList<PacAcademicOutputVo> academicOutputVos = new ArrayList<>();
        list.forEach(item -> {
            PacAcademicOutputVo vo = new PacAcademicOutputVo();
            vo.setId(item.getId());
            vo.setAcTitle(item.getAcTitle());
            vo.setAcFile(item.getAcFile());
            vo.setAcAudit(item.getAcAudit());
            vo.setAcWall(item.getAcWall());
            vo.setStuId(item.getStuId());
            vo.setStuName(item.getStuName());
            vo.setStuNum(item.getStuNum());
            Student student = studentMap.get(item.getStuId().intValue());

            vo.setStuClass(student.getStuClass());
            vo.setStuFaculties(student.getStuFaculties());
            vo.setYearEnrollment(student.getYearEnrollment());
            vo.setCreateTime(item.getCreateTime());
            vo.setAcTime(item.getAcTime());
            vo.setInputValue1(item.getInputValue1());
            vo.setAcDanwei(item.getAcDanwei());
            String instructorTeacherId = item.getInstructorTeacherId();
            List<PacTeacher> teachers = pacTeacherService.listByIds(Arrays.asList(instructorTeacherId.split(",")));
            vo.setTeachers(teachers);

            PacTeacher academicTeacherInfo = pacTeacherService.getAcademicTeacherInfo(student.getClassId());
            vo.setAcademicTeacher(academicTeacherInfo.getTeacherName());

            vo.setPatentNum(item.getAcDanwei());

            // 把团队成员查出来
            List<AcademicOutputParticipationListVo> participants = pacScientificProjectsParticipationService.getParticipants(item.getId());
            vo.setParticipants(participants);

            academicOutputVos.add(vo);
        });

        PageInfo pageInfo = new PageInfo(list);

        TableData<PacAcademicOutputVo> tableData = TableData.<PacAcademicOutputVo>builder()
                .data(academicOutputVos)
                .total(pageInfo.getTotal())
                .build();


        return tableData;
    }

    @Override
    public PacScientificProjects getDetails(PacScientificProjects pacSoftPatent) {
        if (pacSoftPatent.getId() == null) {
            throw new BaseException("id不能为空");
        }
        PacScientificProjects one = lambdaQuery().eq(PacScientificProjects::getId, pacSoftPatent.getId()).one();
        // 把字符串转集合
        String instructorTeacherId = one.getInstructorTeacherId();
        List<String> list = Arrays.asList(instructorTeacherId.split(","));
        List<Long> collect = list.stream().map(id -> Long.valueOf(id)).collect(Collectors.toList());
        one.setTeacherIds(collect);
        List<Long> longs = pacScientificProjectsParticipationService.selectMemberIds(pacSoftPatent.getId());
        one.setMemberIds(longs);
        return one;
    }

    @Override
    public boolean add(PacScientificProjects pacSoftPatent) {
        validateAdd(pacSoftPatent);
        // 插入学生信息
        Long stuId = pacSoftPatent.getStuId();
        Student student = studentService.getById(stuId);
        pacSoftPatent.setStuName(student.getStuName());
        pacSoftPatent.setStuNum(student.getStuNum());
        pacSoftPatent.setStuArea(student.getSmallTeam());
        List<Long> teacherIds = pacSoftPatent.getTeacherIds();
        // 逗号分隔
        String teacherIdsStr = StringUtils.join(teacherIds, ",");
        pacSoftPatent.setInstructorTeacherId(teacherIdsStr);

        PacTeacher pacTeacher = pacTeacherService.getAcademicTeacherInfo(student.getClassId());
        if (pacTeacher != null) {
            pacSoftPatent.setAcademicTeacherId(pacTeacher.getId().longValue());
        }
        if (Objects.nonNull(pacSoftPatent.getAcFile())) {
            FileTypeEnum fileTypeName = FileTypeUtils.getFileTypeName(pacSoftPatent.getAcFile());
            pacSoftPatent.setAcFileType(fileTypeName.getCode());
        }

        if (save(pacSoftPatent)) {
            PacAuditRecords pacAuditRecords = getPacAuditRecords(pacSoftPatent, student);
            pacAuditRecordsService.add(pacAuditRecords);
        }
        return true;
    }

    @Override
    public boolean addByStu(PacScientificProjects pacSoftPatent) {
        Student myInfo = CommonUtils.getStudent();
        // 插入学生信息
        Student student = studentService.getById(pacSoftPatent.getStuId());

        Boolean isIncludeMe = myInfo.getId().equals(pacSoftPatent.getStuId().intValue());

        validateAdd(pacSoftPatent);
        insertRecord(pacSoftPatent, student);
        if (pacSoftPatent.getMemberIds() != null) {
            List<Student> students = studentService.selectByStuIds(pacSoftPatent.getMemberIds());
            if(!students.isEmpty()){
                // 查看团队成员是否包含自己
                if(!isIncludeMe){
                    isIncludeMe = students.stream().anyMatch(item -> item.getId().equals(myInfo.getId()));
                    if(!isIncludeMe){
                        throw new BaseException("成员中至少包含自己");
                    }
                }
            }
            students.forEach(item -> {
                PacScientificProjectsParticipation pacAcademicOutputParticipation = new PacScientificProjectsParticipation();
                pacAcademicOutputParticipation.setOutputId(pacSoftPatent.getId());
                pacAcademicOutputParticipation.setParticipantId(item.getId().longValue());
                pacScientificProjectsParticipationService.join(pacAcademicOutputParticipation);
            });
        }
        return true;
    }

    private void insertRecord(PacScientificProjects pacSoftPatent, Student student) {
        // 插入学生信息
        pacSoftPatent.setStuName(student.getStuName());
        pacSoftPatent.setStuNum(student.getStuNum());
        pacSoftPatent.setStuArea(student.getSmallTeam());
        pacSoftPatent.setStuId(student.getId().longValue());

        List<Long> teacherIds = pacSoftPatent.getTeacherIds();
        // 逗号分隔
        String teacherIdsStr = StringUtils.join(teacherIds, ",");
        pacSoftPatent.setInstructorTeacherId(teacherIdsStr);

        PacTeacher pacTeacher = pacTeacherService.getAcademicTeacherInfo(student.getClassId());
        if (pacTeacher != null) {
            pacSoftPatent.setAcademicTeacherId(pacTeacher.getId().longValue());
        }
        if (Objects.nonNull(pacSoftPatent.getAcFile())) {
            FileTypeEnum fileTypeName = FileTypeUtils.getFileTypeName(pacSoftPatent.getAcFile());
            pacSoftPatent.setAcFileType(fileTypeName.getCode());
        }

        if (save(pacSoftPatent)) {
            PacAuditRecords pacAuditRecords = getPacAuditRecords(pacSoftPatent, student);
            pacAuditRecordsService.add(pacAuditRecords);
        }
    }

    @Override
    public boolean edit(PacScientificProjects pacSoftPatent) {
        Long id = pacSoftPatent.getId();

        PacScientificProjects byId = getById(id);
        if (byId == null) {
            throw new BaseException("记录异常");
        }

        // 判断状态，如果已通过不让他更新
        if (byId.getAcAudit().equals(AuditStatusEnum.AUDITED.getCode())) {
            throw new BaseException("已通过，请勿修改");
        }

        Long stuId = pacSoftPatent.getStuId();
        Student student = studentService.getById(stuId);
        pacSoftPatent.setStuName(student.getStuName());
        pacSoftPatent.setStuNum(student.getStuNum());
        pacSoftPatent.setStuArea(student.getSmallTeam());

        List<Long> teacherIds = pacSoftPatent.getTeacherIds();
        // 逗号分隔
        String teacherIdsStr = StringUtils.join(teacherIds, ",");
        pacSoftPatent.setInstructorTeacherId(teacherIdsStr);

        PacTeacher pacTeacher = pacTeacherService.getAcademicTeacherInfo(student.getClassId());
        if (pacTeacher != null) {
            pacSoftPatent.setAcademicTeacherId(pacTeacher.getId().longValue());
        }

        if (Objects.nonNull(pacSoftPatent.getAcFile())) {
            FileTypeEnum fileTypeName = FileTypeUtils.getFileTypeName(pacSoftPatent.getAcFile());
            pacSoftPatent.setAcFileType(fileTypeName.getCode());
        }

        pacSoftPatent.setAcAudit(AuditStatusEnum.UNAUDITED.getCode());

        if (updateById(pacSoftPatent)) {
            PacAuditRecords pacAuditRecords = getPacAuditRecords(pacSoftPatent, student);
            pacAuditRecordsService.updateByRecord(pacAuditRecords);
        }

        // 先删除团队成员
        pacScientificProjectsParticipationService.deleteByOutPutId(pacSoftPatent.getId());
        // 重新添加
        if (pacSoftPatent.getMemberIds() != null) {
            List<Student> students = studentService.selectByStuIds(pacSoftPatent.getMemberIds());
            students.forEach(item -> {
                PacScientificProjectsParticipation pacAcademicOutputParticipation = new PacScientificProjectsParticipation();
                pacAcademicOutputParticipation.setOutputId(pacSoftPatent.getId());
                pacAcademicOutputParticipation.setParticipantId(item.getId().longValue());
                pacScientificProjectsParticipationService.join(pacAcademicOutputParticipation);
            });
        }
        return true;
    }

    @Override
    public boolean editByStu(PacScientificProjects pacSoftPatent) {
        Student student = CommonUtils.getStudent();
        Long id = pacSoftPatent.getId();

        PacScientificProjects byId = getById(id);
        if (byId == null) {
            throw new BaseException("记录异常");
        }

        // 判断状态，如果已通过不让他更新
        if (byId.getAcAudit().equals(AuditStatusEnum.AUDITED.getCode())) {
            throw new BaseException("已通过，请勿修改");
        }
        pacSoftPatent.setStuName(student.getStuName());
        pacSoftPatent.setStuNum(student.getStuNum());
        pacSoftPatent.setStuArea(student.getSmallTeam());
        pacSoftPatent.setStuId(student.getId().longValue());
        List<Long> teacherIds = pacSoftPatent.getTeacherIds();
        // 逗号分隔
        String teacherIdsStr = StringUtils.join(teacherIds, ",");
        pacSoftPatent.setInstructorTeacherId(teacherIdsStr);

        PacTeacher pacTeacher = pacTeacherService.getAcademicTeacherInfo(student.getClassId());
        if (pacTeacher != null) {
            pacSoftPatent.setAcademicTeacherId(pacTeacher.getId().longValue());
        }

        if (Objects.nonNull(pacSoftPatent.getAcFile())) {
            FileTypeEnum fileTypeName = FileTypeUtils.getFileTypeName(pacSoftPatent.getAcFile());
            pacSoftPatent.setAcFileType(fileTypeName.getCode());
        }

        pacSoftPatent.setAcAudit(AuditStatusEnum.UNAUDITED.getCode());

        if (updateById(pacSoftPatent)) {
            PacAuditRecords pacAuditRecords = getPacAuditRecords(pacSoftPatent, student);
            pacAuditRecordsService.updateByRecord(pacAuditRecords);
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean delete(PacScientificProjects pacSoftPatent) {
        if (pacSoftPatent.getId() == null) {
            throw new BaseException("id不能为空");
        }
        if (removeById(pacSoftPatent)) {
            // 同时删除审批记录
            pacAuditRecordsService.deleteByOutPutId(pacSoftPatent.getId(), AuditTypeEnum.PAC_WALL_TYPE_CREATION.getCode());
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean wall(AcademicCommonVo academicCommonVo) {
        List<Long> ids = academicCommonVo.getIds();
        if (ids != null && !ids.isEmpty()) {
            List<PacScientificProjects> list = new ArrayList<>();
            ids.forEach(item -> {
                PacScientificProjects pacSoftPatent = new PacScientificProjects();
                pacSoftPatent.setId(item);
                pacSoftPatent.setAcWall(2);
                list.add(pacSoftPatent);
            });
            updateBatchById(list);
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean unWall(AcademicCommonVo academicCommonVo) {
        List<Long> ids = academicCommonVo.getIds();
        if (ids != null && !ids.isEmpty()) {
            List<PacScientificProjects> list = new ArrayList<>();
            ids.forEach(item -> {
                PacScientificProjects pacAcademicOutput = new PacScientificProjects();
                pacAcademicOutput.setId(item);
                pacAcademicOutput.setAcWall(1);
                list.add(pacAcademicOutput);
            });
            updateBatchById(list);
        }
        return true;
    }

    @Override
    public List<PacScientificProjects> myList(PacScientificProjects pacAcademicOutput) {
        Student student = CommonUtils.getStudent();
        if (student != null) {
//            List<PacScientificProjects> list = lambdaQuery()
//                    .likeRight(StringUtils.isNotEmpty(pacAcademicOutput.getAcTitle()),
//                            PacScientificProjects::getAcTitle, pacAcademicOutput.getAcTitle())
//                    .eq(Objects.nonNull(pacAcademicOutput.getAcAudit()), PacScientificProjects::getAcAudit, pacAcademicOutput.getAcAudit())
//                    .eq(Objects.nonNull(pacAcademicOutput.getAcFileType()), PacScientificProjects::getAcFileType, pacAcademicOutput.getAcFileType())
//                    .eq(PacScientificProjects::getStuId, student.getId())
//                    .between(Objects.nonNull(pacAcademicOutput.getStartTime()), PacScientificProjects::getCreateTime, pacAcademicOutput.getStartTime(), pacAcademicOutput.getEndTime())
//                    .list();
            pacAcademicOutput.setStuId(student.getId().longValue());
            List<PacScientificProjects> list = baseMapper.myList(pacAcademicOutput);

            PacTeacher pacTeacher = pacTeacherService.getAcademicTeacherInfo(student.getClassId());


            list.forEach(item -> {
                String instructorTeacherId = item.getInstructorTeacherId();
                List<PacTeacher> teachers = pacTeacherService.listByIds(Arrays.asList(instructorTeacherId.split(",")));
                item.setTeachers(teachers);
                item.setStuFaculties(student.getStuFaculties());
                item.setStuClass(student.getStuClass());
                item.setYearEnrollment(student.getYearEnrollment());
                if(pacTeacher != null){
                    item.setAcademicTeacher(pacTeacher.getTeacherName());
                }
                // 把团队成员查出来
                List<AcademicOutputParticipationListVo> participants = pacScientificProjectsParticipationService.getParticipants(item.getId());
                item.setParticipants(participants);
            });
            return list;
        }
        return Collections.emptyList();
    }

    @Override
    public void audit(PacScientificProjects output) {
        updateById(output);
    }

    @Override
    public List<HonorWallTopThreeVo> getTopThree(WallTopThree builder) {
        List<PacScientificProjects> list = lambdaQuery()
                .eq(PacScientificProjects::getAcWall, WallStateEnum.WALL_STATE_YES.getCode())
                .eq(Objects.nonNull(builder.getFileType()), PacScientificProjects::getAcFileType, builder.getFileType())
                .eq(Objects.nonNull(builder.getStuId()), PacScientificProjects::getStuId, builder.getStuId())
                .between(Objects.nonNull(builder.getStartTime()), PacScientificProjects::getCreateTime, builder.getStartTime(), builder.getEndTime())
                .orderByDesc(PacScientificProjects::getCreateTime)
                .last("LIMIT 3")
                .list();

        if (list != null && !list.isEmpty()) {
            return list.stream().map(item -> {
                HonorWallTopThreeVo honorWallTopThreeVo = new HonorWallTopThreeVo();
                honorWallTopThreeVo.setAcTitle(item.getAcTitle());
                honorWallTopThreeVo.setAcFile(item.getAcFile());
                honorWallTopThreeVo.setAcFileType(item.getAcFileType());
                honorWallTopThreeVo.setStuName(item.getStuName());
                return honorWallTopThreeVo;
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public List<HonorWallTopThreeVo> getStuHonorList(WallTopThree wallTopThree) {
        List<PacScientificProjects> list = lambdaQuery()
                .eq(Objects.nonNull(wallTopThree.getFileType()), PacScientificProjects::getAcFileType, wallTopThree.getFileType())
                .eq(Objects.nonNull(wallTopThree.getStuId()), PacScientificProjects::getStuId, wallTopThree.getStuId())
                .orderByDesc(PacScientificProjects::getCreateTime)
                .list();

        if (list != null && !list.isEmpty()) {
            return list.stream().map(item -> {
                HonorWallTopThreeVo honorWallTopThreeVo = new HonorWallTopThreeVo();
                honorWallTopThreeVo.setAcTitle(item.getAcTitle());
                honorWallTopThreeVo.setAcFile(item.getAcFile());
                honorWallTopThreeVo.setAcFileType(item.getAcFileType());
                honorWallTopThreeVo.setStuName(item.getStuName());
                return honorWallTopThreeVo;
            }).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    @Override
    public long countByAudit() {
        long count = lambdaQuery().eq(PacScientificProjects::getAcAudit, 2).count();
        return count;
    }

    @Override
    public List<PacScientificProjects> selectStuTop5(Integer id) {
        List<PacScientificProjects> list = lambdaQuery()
                .eq(PacScientificProjects::getAcFileType, FileTypeEnum.IMAGE.getCode())
                .eq(PacScientificProjects::getAcAudit, AuditStatusEnum.AUDITED.getCode())
                .eq(PacScientificProjects::getStuId, id)
                .orderByDesc(PacScientificProjects::getCreateTime)
                .last("LIMIT 5")
                .list();

        return list;
    }

    /**
     * 新增校验
     *
     * @param pacAcademicOutput
     */
    private void validateAdd(PacScientificProjects pacAcademicOutput) {
        if (pacAcademicOutput.getAcTime() == null) {
            throw new BaseException("成果时间不能为空");
        }
    }

    private static PacAuditRecords getPacAuditRecords(PacScientificProjects pacAcademicOutput, Student student) {
        PacAuditRecords pacAuditRecords = new PacAuditRecords();
        pacAuditRecords.setAuditType(AuditTypeEnum.PAC_WALL_TYPE_CREATION.getCode());
        pacAuditRecords.setAuditStu(pacAcademicOutput.getStuName());
        pacAuditRecords.setAuditStuClass(student.getStuClass());
        pacAuditRecords.setAuditFile(pacAcademicOutput.getAcFile());
        pacAuditRecords.setAuditTitle(pacAcademicOutput.getAcTitle());
        pacAuditRecords.setAuditStuId(pacAcademicOutput.getStuId());
        pacAuditRecords.setAuditRecordId(pacAcademicOutput.getId());
        pacAuditRecords.setAuditFileType(pacAcademicOutput.getAcFileType());
        return pacAuditRecords;
    }
}




